import prompts from 'prompts'
import { red } from 'kolorist'
import deploy from './core/deploy'

import { checkDeployConfig, CONFIG, checkConfigScheme } from './utils/format'

const promptsHandle = (config: prompts.PromptObject<string> | Array<prompts.PromptObject<string>>) => {
  return prompts(config, {
    onCancel: (e) => {
      throw new Error(red('✖') + ' 操作被取消')
    }
  })
}

export default async (targetPath: string) => {
  const deployConfigs = checkDeployConfig(targetPath)

  if (!deployConfigs.length) {
    return
  }

  let commandData:CONFIG | null = null

  // 多条配置信息进行select选择
  try {
    if (deployConfigs.length > 1) {
      const { command } = await promptsHandle([{
        type: 'select',
        name: 'command',
        message: '请选择部署环境',
        choices: deployConfigs.map((item) => ({
          title: item.name,
          value: item
        }))
      }])

      commandData = command
    } else {
      // 单条配置信息进行confirm确认
      commandData = deployConfigs[0]

      const { sure } = await promptsHandle([{
        type: 'confirm',
        name: 'sure',
        initial: true,
        message: () => `将${(commandData as CONFIG).projectName}项目是否部署到${(commandData as CONFIG).name}？`
      }])

      if (!sure) return console.log(red('✖') + ' 已取消部署')
    }
  } catch (error) {
    console.log((error as Error).message)
    return
  }

  checkConfigScheme((commandData as CONFIG))
  deploy((commandData as CONFIG))
}
